<template>
  <Dialog v-model="dialogVisible" :title="title" width="500">
    <el-form
      ref="formRef"
      style="max-width: 600px"
      :model="numberValidateForm"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="组名" prop="name" :rules="[{ required: true, message: '组名不能为空' }]">
        <el-input v-model.trim="numberValidateForm.name" type="text" clearable maxlength="30" />
      </el-form-item>
      <el-form-item
        label="排序"
        prop="sort"
        :rules="[
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序必须是个数字' }
        ]"
      >
        <el-input v-model.number="numberValidateForm.sort" type="text" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" style="width: 100%" @click="submitForm(formRef)">
          提交
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as Assistant from '@/api/service/assistant/index'

const dialogVisible = ref(false)
const formRef = ref(null)
const title = ref('')
const typeList = ref('')
const assistantId = ref('')

const numberValidateForm = reactive({
  name: '',
  sort: ''
})

const open = (type, val) => {
  title.value = type == 'create' ? '添加分组' : '编辑组名'
  typeList.value = type
  if (type == 'update') {
    numberValidateForm.name = val.name
    numberValidateForm.sort = val.sort
    assistantId.value = val.id
  }
  dialogVisible.value = true
}

const emit = defineEmits(['customerServiceList'])

/* 提交 */
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if (typeList.value == 'create') {
        const data = await Assistant.createAssistantGroup(numberValidateForm)
        if (data) ElMessage.success('添加成功')
        resetForm(formRef.value)
        dialogVisible.value = false
        emit('customerServiceList')
      } else {
        const data = await Assistant.updateAssistantGroup({
          ...numberValidateForm,
          id: assistantId.value
        })
        if (data) ElMessage.success('更新成功')
        resetForm(formRef.value)
        dialogVisible.value = false
        emit('customerServiceList')
      }
    } else {
      return false
    }
  })
}
/* 清空 */
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
defineExpose({
  open
})
</script>

<style lang="scss" scoped>
p {
  margin: 0;
  margin-bottom: 10px;
  font-size: 14px;
  color: #515a6e;
}
:deep(.el-dialog__body) {
  padding: 0 20px;
}
</style>
